#!/usr/bin/env bash
set -e

/etc/init.d/nginx 				start
/etc/init.d/redis-server	start
/etc/init.d/ssh 					start

if [ ! -f /root/.ssh/known_hosts ]; then
	# 把宿主机的ssh key拷贝进来
	ssh-keyscan -H localhost >> ~/.ssh/known_hosts
	ssh-keyscan -H gitlab.wikiflyer.cn >> ~/.ssh/known_hosts
fi

export PG_DATADIR=/var/lib/postgresql/9.6/main
export PG_CONFIGDIR=/etc/postgresql/9.6/main

mkdir -p ${PG_DATADIR}
chown postgres:postgres ${PG_DATADIR}

if [ ! -f /data/.inited ];then
	su postgres -c "/usr/lib/postgresql/9.6/bin/initdb -D /var/lib/postgresql/9.6/main -U postgres"
	chown -R postgres:postgres ${PG_DATADIR}
	/etc/init.d/postgresql start

	su postgres -c "psql -Upostgres -c \"ALTER USER postgres WITH SUPERUSER PASSWORD 'postgres'\""

	/etc/init.d/postgresql stop

	sed -ri "s/local.*(peer|trust)/local\tall\tall\tmd5/g" ${PG_DATADIR}/pg_hba.conf

	# ln -sf ${PG_DATADIR}/postgresql.conf ${PG_CONFIGDIR}/postgresql.conf
	ln -sf ${PG_DATADIR}/pg_hba.conf ${PG_CONFIGDIR}/pg_hba.conf
	# ln -sf ${PG_DATADIR}/pg_ident.conf ${PG_CONFIGDIR}/pg_ident.conf

	export PGPASSWORD=postgres

	/etc/init.d/postgresql start

	psql -Upostgres -c "CREATE DATABASE pdca"
	psql -Upostgres -c "CREATE DATABASE kanban"

	# TODO: 把mina和部署的文件拷贝进来
	# cp /scripts/mina/* /data/

	# TODO: 部署初始化

	# TODO: 部署

	echo 'init .inited stop'
	touch /data/.inited
 else
 	ln -sf ${PG_DATADIR}/pg_hba.conf ${PG_CONFIGDIR}/pg_hba.conf
	/etc/init.d/postgresql start
	echo '.inited is exists'
fi

# 保持持续运行
/bin/bash
